package com.gjs.cd.manager;

import com.gjs.cd.pojo.entity.Code;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 激活码生成类
 */
public class MakeCode {
    /**
     *
     * @param tableName，表名前缀（激活码的前四位）
     * @param quater，季度
     * @param num，激活码数量
     * @return
     */
    public List<Code> createCode(String tableName, Long batchId,int quater, int num){
        List<Code> list = new ArrayList<>();
        for (int i=0;i<num;i++){
            Code code = new Code();
            String activationCode = addHLine(tableName+makeUniqueCode()+quater);
            System.out.println("激活码："+activationCode);
            code.setActivationCode(activationCode);
            code.setBatchId(batchId);
            code.setCreateTime(LocalDateTime.now());
            list.add(code);
        }
        return list;
    }

    /**
     * 转为大写并添加横线
     * @param code
     * @return
     */
    private String addHLine(String code){
        StringBuffer stringBuffer = new StringBuffer(code.toUpperCase());
        for (int i=0;i<3;i++){
            stringBuffer.insert(4*(i+1)+i,"-");
        }
        return stringBuffer.toString();
    }

    /**
     * 唯一码端的生成
     * @return
     */
    private String makeUniqueCode(){
        char[] baseStr = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        Long currentTime = System.nanoTime();//获取当前时间，纳秒
        String currentTime36 = Long.toString(currentTime,36);//将获取的当前时间转为36进制,9位
        Random random = new Random();
        String randomString = "";
        int count = 11 - currentTime36.length();
        for (int i = 0;i < count;i++){
            randomString += baseStr[random.nextInt(36)];
        }
        return currentTime36+randomString;
    }
}
